<?php
class UnitsMarket {
	
	public static function buyUnit(User $user, $unitID, $number) {
		
		if(get_class($user) != "User") {
			
			throw new Exception("First parameter for function buyUnit should be of type User");
		}
		
		if($unitID<0) {
			
			throw new Exception("Second parameter for function buyUnit should be a positive integer number!");
		}
		
		if($number<0) {
				
			throw new Exception("Third parameter for function buyUnit should be a positive integer number!");
		}
		
		$units = DBUtils::getUnits();
		$price = null;
		$attack = null;
		$defence = null;
		$name = null;
		foreach($units as $unit) {
			
			if($unit['unit_id'] == $unitID) {
				
				$price = $unit['price'];
				$attack = $unit['attack'];
				$defence = $unit['deffence'];
				
			}
		}
		
		if($price == null) {
			
			throw new Exception("Parameter for Unit ID is invalid. There is no such unit in a market!");
		}
		
		$check = $number * $price;
		$userMoney = $user->getMoney();
		
		if($check > $userMoney) {
			
			echo "Нямате достатъчно пари, за да наемете толкова програмисти!";
			
		} else {
			
			$user->setAttack($user->getAttack() + ($attack*$number));
			$user->setDefence($user->getDefence() + ($defence*$number));
			$user->setMoney($userMoney-$check);
			
			if($number == 1) {
				
				echo "Честито, успешно наехте $number програмист във вашия екип.";

			} else {
				
				echo "Честито, успешно наехте $number програмисти във вашия екип.";
			}
			
		}
	}
}